package cat.joronya.supermanager;

import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;

/**
 * Preference activity to handle widget preferences.
 * @author pol
 *
 */
public class SupervermutWidgetConfigurationActivity extends PreferenceActivity 
{
	public static final String TAG = "supermanager";
	
	private static final String PREFS_NAME = "cat.joronya.supermanager.SupermanagerWidgetProvider";
	
	// prefix per afegir a les keys per cada widget
	private static final String PREF_PREFIX_KEY = "widget_";
	
	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		// Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if they press the back button.
        setResult(RESULT_CANCELED);
        
        // Load the preferences from an XML resource
		addPreferencesFromResource(R.xml.widget_preferences);
		
		// registrem l'onclick al preference button
		Preference button = (Preference)findPreference("create_button");
		button.setOnPreferenceClickListener(mOnPreferenceClickListener);
        
		 // Find the widget id from the intent. 
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) 
        {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, 
            					AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        
        // If they gave us an intent without the widget id, just bail.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) 
        {
            finish();
        }
	}
	
	Preference.OnPreferenceClickListener mOnPreferenceClickListener = 
		new Preference.OnPreferenceClickListener() 
	{
		public boolean onPreferenceClick(Preference arg0) { 
			//code for what you want it to do 
			return true;
		}
	};
	
	// Write the team to the SharedPreferences object for this widget
    static void saveTitlePref(Context context, int appWidgetId, String text) 
    {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.putString(PREF_PREFIX_KEY + appWidgetId, text);
        prefs.commit();
    }

    // Read the team from the SharedPreferences object for this widget.
    // If there is no preference saved, return null.
    static String loadTitlePref(Context context, int appWidgetId) 
    {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        String idequ = prefs.getString(PREF_PREFIX_KEY + appWidgetId, null);
        if( idequ != null )
        {
            return idequ;
        }
        else 
        {
            return null;
        }
    }
}
